# coding=utf-8
import json

from boto3 import Session
aws_key = "AKIAIOFGB7H4GDSE5NJQ"
aws_secret = "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"
session = Session(aws_access_key_id=aws_key, aws_secret_access_key=aws_secret)
print("connected")
s3 = session.resource('s3')
s3_client = session.client('s3')
print("connected")
# s3.Bucket('test4jimmy').upload_file('done_node.json', 'folder/done_node.json')
# s3.Object("test4jimmy", 'done_node.json').upload_file('folder1/abc/done_node.json')
# s3_client.put_object(Bucket='test4jimmy', Key='folder1/abc/')
# listing buckets
# test4jimmy_bucket = None
# for bucket in s3.buckets.all():
#     print('bucket name:%s' % bucket.name)
#     if bucket.name == "test4jimmy":
#         test4jimmy_bucket = bucket

# json test # https://stackoverflow.com/questions/40336918/how-to-write-a-file-or-data-to-an-s3-object-using-boto3
bucket = s3.Bucket("test4jimmy")
json.load_s3 = lambda f: json.load(bucket.Object(key=f).get()["Body"])
json.dump_s3 = lambda obj, f: bucket.Object(key=f).put(Body=json.dumps(obj))
data = {"test":0}
json.dump_s3(data, "key.json")  # saves json to s3://bucket/key
data = json.load_s3("key.json")  # read json from s3://bucket/key
# download file
# print('downloading file...')
s3.Bucket('test4jimmy').download_file('folder/done_node.json', 'aaa.json')
# s3.Object("test4jimmy", 'done_node.json').download_file('done_node_downloaded.json')

# upload file
print('uploading file...')
s3.Bucket('test4jimmy').upload_file('done_node.json', 'done_node.json')
# s3_client.put_object(Bucket="test4jimmy",Key=directoryname/filename)
# s3.Object("test4jimmy", 'done_node.json').upload_file('done_node.json')

# upload file with folder
print('uploading file with folder...')
s3.Bucket('test4jimmy').upload_file('done_node.json', 'folder/done_node.json')
# s3.Object("test4jimmy", 'done_node.json').upload_file('/test_folder/done_node.json')
# k = s3.Bucket("test4jimmy").new_key('abc/123/')
# k.set_contents_from_string('')
# s3.put_object(Bucket='mybucketName', Key='folder1/abc/')

# exists file
print('existing file...')
bucket = s3.Bucket("test4jimmy")
for obj in bucket.objects.filter(Prefix='done_node.json'):
    if obj.key == 'done_node.json':
        print('file exists!')
    else:
        print('file not exists!')